package com.ly.jwt.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ly.jwt.db.entity.UserAccount;
import com.ly.jwt.db.entity.UserLog;
import com.ly.jwt.db.entity.UserLogType;
import com.ly.jwt.db.mapper.UserAccountMapper;
import com.ly.jwt.db.mapper.UserLogMapper;
import com.ly.jwt.service.UserAccountService;
import com.ly.jwt.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserAccountServiceImpl implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    UserLogMapper userLogMapper;

    //登录
    @Override
    // isolation:事务的隔离级别，此处使用后端数据库的默认隔离级别,
    // propagation: 如果当前没有事务，就新建一个事务，如果已经存在一个事务中，加入到这个事务中(常见)。
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
    public JsonResult<?> login(UserAccount userAccount) {
        //传入对象
        if (userAccount == null) {
            throw new BaseException("4001","传入对象为空");
        }
        //账号
        String username = userAccount.getUsername();
        if (StringUtils.isBlank(username)) {
            throw new BaseException("4001","账号为空");
        }
        //根据用户名查询信息==>密码盐
        UserAccount userAccount1 = userAccountMapper.selectByUsername(username);
        //密码
        String password = userAccount.getPassword();
        if (StringUtils.isBlank(password)) {
            throw new BaseException("4001","密码为空");
        }
        //用户输入密码，和根据输入用户名从数据库进行寻找密码盐
        String password1 = PwdTool.getHMAC(password, userAccount1.getPwdKey());
        //赋值根据密码盐加密后的密码
        userAccount.setPassword(password1);
        //高根据用户名和密码进行数据库比对查询
        UserAccount userAccount2 = userAccountMapper.login(userAccount);
        //如果不为空就生成token
        if (ObjectUtil.isEmpty(userAccount2)) {
            throw new BaseException("4001","用户名或密码错误");
        }
        //生成token
        String token = TokenUtil.sign(userAccount1);
        if (StringUtils.isBlank(token)) {
            throw new BaseException("4001","token生成失败");
        }
        //添加日志
        UserLog userLog = new UserLog();
        userLog.setReqIp(IpUtils.getIP());
        userLog.setType(UserLogType.LOGIN);
        userLog.setText("账号"+userAccount.getUsername()+"进行了登录");
        userLog.setUid(String.valueOf(userAccount2.getId()));
        userLog.setCreateTime(new Date());
        int i = userLogMapper.insertSelective(userLog);
        if (i != 1) {
            throw new BaseException("4001","添加失败");
        }
        Map<String,Object> map = new HashMap();
        map.put("token",token);
        return new JsonResult<>(map);
    }

    //查询全部
    @Override
    public List<UserAccount> selectAll() {
        return userAccountMapper.selectAll();
    }

    //添加账号
    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
    public JsonResult<?> insertSelective(UserAccount userAccount) {
        //传入对象
        if (ObjectUtil.isEmpty(userAccount)) {
            throw new BaseException("4001","未获取到参数");
        }
        //账号
        String username = userAccount.getUsername();
        if (ObjectUtil.isEmpty(username)) {
            throw new BaseException("4001","未获取到username");
        }
        //根据用户名进行查询，不允许重复
        UserAccount userAccount1 = userAccountMapper.selectByUsername(username);
        if (!ObjectUtil.isEmpty(userAccount1)) {
            throw new BaseException("4001","用户名重复");
        }
        //密码
        String password = userAccount.getPassword();
        if (ObjectUtil.isEmpty(password)) {
            throw new BaseException("4001","未获取到password");
        }
        //密码盐==>调用工具类进行获取
        String pwdKey = PwdTool.getRandomSalt();
        userAccount.setPwdKey(pwdKey);
        //使用密码盐加密后的密码
        String password1 = PwdTool.getHMAC(password, pwdKey);
        //赋值新密码
        userAccount.setPassword(password1);
        //创建时间
        userAccount.setCreateTime(new Date());
        int i = userAccountMapper.insertSelective(userAccount);
        if (i != 1) {
            throw new BaseException("4001","添加失败");
        }
        //添加日志
        UserLog userLog = new UserLog();
        userLog.setReqIp(IpUtils.getIP());
        userLog.setType(UserLogType.ZHUC);
        userLog.setText("账号"+userAccount.getUsername()+"进行了注册");
        userLog.setUid(String.valueOf(userAccount.getId()));
        userLog.setCreateTime(new Date());
        int j = userLogMapper.insertSelective(userLog);
        if (j != 1) {
            throw new BaseException("4001","添加失败");
        }
        Map<String,Object> map = new HashMap();
        map.put("id",userAccount.getId());
        map.put("username",userAccount.getUsername());
        return new JsonResult<>(map);
    }
}